/**
 * Notes: 日志管理定时任务
 * Ver : CCMiniCloud Framework 2.5.0 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2023-09-01 20:00:00 
 */

const BaseTask = require('./base_task.js');
const LogModel = require('../config/models_config').log_model;
const LogCache = require('../cache/log_cache.js');
const CacheModel = require('../config/models_config').cache_model;
const timeUtil = require('../../helpers/time_util.js');

/**
 * 日志管理定时任务
 * 负责定期清理过期日志和提交日志缓存
 */
class LogTask extends BaseTask {

    constructor() {
        // 任务名称
        super('日志管理');
        
        // 设置执行间隔 (1小时)
        this.interval = 60 * 60 * 1000;
    }

    /**
     * 执行定时任务
     */
    async exec() {
        try {
            await this.commitLogCache();
            await this.cleanExpiredLogs();
            await this.cleanExpiredCache();
            await this.smartLogClean();
        } catch (error) {
            console.error('日志管理定时任务执行失败:', error);
        }
    }
    
    /**
     * 提交日志缓存
     */
    async commitLogCache() {
        try {
            await LogCache.commit();
            console.log('提交日志缓存完成');
        } catch (error) {
            console.error('提交日志缓存失败:', error);
        }
    }
    
    /**
     * 清理过期日志
     */
    async cleanExpiredLogs() {
        try {
            await LogCache.cleanExpiredLogs();
            console.log('清理过期日志完成');
        } catch (error) {
            console.error('清理过期日志失败:', error);
        }
    }
    
    /**
     * 智能日志清理
     */
    async smartLogClean() {
        try {
            await LogCache.smartClean();
            console.log('智能日志清理完成');
        } catch (error) {
            console.error('智能日志清理失败:', error);
        }
    }
    
    /**
     * 清理过期缓存
     */
    async cleanExpiredCache() {
        try {
            const now = timeUtil.time();
            await CacheModel.del({
                CACHE_EXPIRE_TIME: ['<', now]
            }, true);
            console.log('清理过期缓存完成');
        } catch (error) {
            console.error('清理过期缓存失败:', error);
        }
    }
}

module.exports = LogTask; 